package dryven.reflection;

import java.util.LinkedList;
import java.util.List;

public class ClassTypeRef implements TypeRef {

	private Class<?> _class;
	private List<TypeRef> _cachedInterfaces;
	
	public ClassTypeRef(Class<?> clazz) {
		super();
		_class = clazz;
	}

	@Override
	public int getArrayDimensions() {
		if(_class.isArray()) {
			int depth = 1;
			Class<?> c = _class.getComponentType();
			while(c.isArray()) {
				++depth;
				c = c.getComponentType();
			}
			return depth;
		} else {
			return 0;
		}
	}

	@Override
	public Iterable<TypeRef> getGenericTypeParams() {
		return null;
	}

	@Override
	public Class<?> getTypeClass() {
		return _class;
	}

	@Override
	public String getTypeName() {
		return _class.getName();
	}

	@Override
	public boolean isArray() {
		return _class.isArray();
	}

	@Override
	public boolean isGeneric() {
		return _class.getTypeParameters()!=null && _class.getTypeParameters().length!=0;
	}

	@Override
	public boolean isPrimitive() {
		return _class.isPrimitive();
	}

	@Override
	public Iterable<TypeRef> getDeclaredInterfaces() {
		if(_cachedInterfaces==null) {
			_cachedInterfaces = new LinkedList<TypeRef>();
			for (Class<?> iface : _class.getInterfaces()) {
				_cachedInterfaces.add(new ClassTypeRef(iface));
			}
		}
		return _cachedInterfaces;
	}

	@Override
	public TypeRef getSuperType() {
		return new ClassTypeRef(_class.getSuperclass());
	}

	@Override
	public boolean implementsInterface(TypeRef t) {
		Class<?> b = t.getTypeClass();
		return b.isInterface() && b.isAssignableFrom(_class);
	}

	@Override
	public boolean inheritsFromType(TypeRef t) {
		Class<?> b = t.getTypeClass();
		return !b.isInterface() && b.isAssignableFrom(_class);
	}

}
